#include"loginclient.h"
#include"task.h"
#include <sys/socket.h>
//生成密文
void generate_ciphertext(char *salt,const char *passwd,char *ciphertext)
{
    struct crypt_data data;
    memset(&data,0,sizeof(data));
    char *p=crypt_r(passwd,salt,&data);
    if(p==NULL)
    {
        return ;
    }
    strncpy(ciphertext,p,1024);
}
int userregister(int netfd,const char *username,const char *password)
{
    train_t train;
    //发送用户名
    bzero(&train,sizeof(train));
    strcpy(train.data,username);
    train.length=strlen(train.data);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);
    bzero(&train,sizeof(train));
    //接收
    recvn(netfd, &train.length, sizeof(train.length));
    if(train.length==0)
    {
        printf("该用户已存在\n");
        return -1;
    }
    bzero(&train,sizeof(train));
    strcpy(train.data,password);
    train.length=strlen(train.data);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);
    printf("注册成功\n");
    return 0;
}
int userlogin(int netfd,const char *username,const char *password)
{
    train_t train;
    bzero(&train,sizeof(train));
    strcpy(train.data,username);
    train.length=strlen(train.data);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);
    bzero(&train,sizeof(train));
    recvn(netfd, &train.length, sizeof(train.length));
    //printf("%d\n",train.length);
    if(train.length==0)
    {
        printf("该用户不存在\n");
        return -1;
    } 
    recvn(netfd,train.data,train.length);
    char salt[1024]={0};
    strcpy(salt,train.data);
    char password_md5[1024]={0};
    generate_ciphertext(salt, password, password_md5);
    bzero(&train,sizeof(train));
    strcpy(train.data,password_md5);
    train.length=strlen(password_md5);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);
    bzero(&train,sizeof(train));
    recvn(netfd, &train.length, sizeof(train.length));
    recvn(netfd,train.data,train.length);
    //printf("train.length=%d\n", train.length);
    if(train.length!=12)
    {
        return -1;
    }
    //printf("%s\n",train.data);
    return 0;
}
